// 我是客户
import React, { useState,useEffect } from 'react'
import {withRouter} from "react-router-dom"
import {Bottom, InputItem,Button} from "antd-mobile"
import "./onlineService.scss"
import WebSocket from "../WebSocket/Index";
import GoEasy from 'goeasy'
import ReactDom from 'react-dom';
import SockJsClient from 'react-stomp';
import Input from 'antd-mobile/lib/input-item/Input';
import axios from 'axios'
import Header from '../../assets/img/katong.png'
import Kehu from '../../assets/img/110.png'
import { BASE_URL } from '../../utils/requestPath';

var goeasy  = GoEasy.getInstance({
    host:"singapore.goeasy.io",  //若是新加坡东南亚区域：singapore.goeasy.io // 中国区域hangzhou.goeasy.io
    appkey:"BC-61f166d35a9a4283a65a27be605eec34",
    modules:['pubsub']//根据需要，传入‘pubsub’或'im’，或数组方式同时传入
});

const userInfoIns = localStorage.getItem("userInfoIns")
const userIns = JSON.parse(userInfoIns) || {}


const OnlineService = ()=> {
    
    const [ message, setMessage ] = useState([])
    const [ value, setValue ] = useState("")
    const [mes,setMess] = useState([])
    const [user,setUser] = useState({})
    const [txt,setTxt] = useState("")
    const [userInfo,setUserInfo] = useState({})
    useEffect(() => {
       //document.title = "客户"
       //localStorageGet()
       startOnclick()
       getMessage();
       console.log(user)
   })

//    function localStorageGet(){
//        const userInfoIns = localStorage.getItem("userInfoIns")
//        const user = JSON.parse(userInfoIns) || {}
//        setUserInfo(user)
//    }

    
    //断开链接
    function clearOnclick(){
         //断开连接
        goeasy.disconnect({
            onSuccess: function(){
                console.log("断开链接成功")
            },
            onFailed: function(error){
                console.log("Failed to disconnect GoEasy, code:"+error.code+ ",error:"+error.content);
            }
        });
    }

    //启动链接
    function startOnclick(){
        //建立连接
        goeasy.connect({
            id:"002", //pubsub选填，im必填
            data:{"avatar":"/www/xxx.png","nickname":"客户1111111"}, //必须是一个对象，pubsub选填，im必填，用于上下线提醒和查询在线用户列表时，扩展更多的属性
            onSuccess: function () {  //连接成功
            console.log("连接成功") //连接成功
            },
            onFailed: function (error) { //连接失败
            console.log("连接失败 code:"+error.code+ ",error:"+error.content);
            },
            onProgress:function(attempts) { //连接或自动重连中
            console.log("自动重连中", attempts);
            }
        });
        
    }

    //获取用户所在ip地址地理位置
    // async function getUserName(){
    //     //数据库获取用户的信息,username名称
    //     const response = await axios.get(BASE_URL+"/api/user/getid/1");
    //     setUser(response)
    //     console.log(response)
    // }

    //接收消息
   function getMessage(){
        
        var pubsub = goeasy.pubsub;
        const userInfoIns = localStorage.getItem("userInfoIns")
        const userInsts = JSON.parse(userInfoIns) || {}
        pubsub.subscribe({
            // 用户的邮箱地址。。。。。。唯一
            channel: userInsts.zgEmail,//替换为您自己的channel
            onMessage: function (message) {
                console.log("接受客服消息........")
                console.log("Channel:" + message.channel + " content:" + message.content); 
                // setMess([...mes,{"msg":message.content,
                // "Channel":message.channel
                //  }])
                    setMess([...mes,{"msg":message.content,
                    "Channel":message.channel
                    }])
            },
            
            onSuccess: function () {
                console.log("Channel订阅成功。");
            },
            onFailed: function (error) {
                console.log("Channel订阅失败, 错误编码：" + error.code + " 错误信息：" + error.content)
            }
        });
        console.log("获取参数")
    }



    console.log(mes)

    //发送消息
    function sendMessages(){
        const userInfoIns = localStorage.getItem("userInfoIns")
        const userInst = JSON.parse(userInfoIns) || {}
        if(userInst.zgEmail !== ""){
            const sendUser = {name:userInst.zgEmail,message:txt}
            console.log(sendUser)
            var pubsub = goeasy.pubsub;
            pubsub.publish({
                channel: "ezblu",//替换为您自己的channel
                message: JSON.stringify(sendUser),//替换为您想要发送的消息内容
                onSuccess:function(){
                    console.log("消息发布成功。");
                    setMess([...mes,{"msg":txt,
                    "Channel":"ezblu"
                     }])
                },
                onFailed: function (error) {
                    console.log("消息发送失败，错误编码："+error.code+" 错误信息："+error.content);
                }
            });
            setTxt("")
        }
        
    }

    const messageOnChangeItem= (e)=>{
        setTxt(e)
        //console.log(e)
    }


    return (
       <div style={{width:"100%",position:"relative"}}>
            <div style={{textAlign:"center"}}>人工客服</div>
            <div style={{width:"100%",height:305,background:"#fff",borderRadius:1,overflow:"scroll",marginBottom:20}}>{mes.map((v,i)=>{
                return (
                    <div key={i}> 
                        <div> 
                          {v.Channel !== "ezblu"?
                          <div style={{marginTop:20}}> 
                                 <div style={{width:"100%",borderRadius:40,display:"flex",flexDirection:"row"}}>
                                    <div style={{width:40,height:40,borderRadius:40}}>
                                        <img style={{width:"100%",height:"100%"}} src={Header}></img>
                                    </div>

                                     <div>
                                            <h4 style={{color:"rgb(70, 77, 77)",fontWeight:"bold"}}>EZblu客服</h4>
                                        <div style={{color:'rgb(115, 116, 118)',borderRadius:20,display:"flex",flexDirection:"row"}}> 
                                            <h3 style={{padding:5,textAlign:"start",justifyContent:"start",background:"rgb(231, 234, 239)",
                                           alignItems:"start",marginLeft:10,borderRadius:5,wordBreak:"break-word",Width:300}}><a 
                                            style={{}}
                                            >{v.msg}</a></h3>
                                        </div>
                                    </div>    
                                </div>
                            
                        </div>
                        
                        :
                                                
                        <div style={{paddingTop:30,width:"100%",display:"flex",flexDirection:"row",justifyContent:"flex-end",justifySelf:"flex-end"}}> 
                        <div style={{borderRadius:40,display:"flex",flexDirection:"row",justifyContent:"flex-end",justifySelf:"flex-end"}}>     
                           <div style={{display:"flex",flexDirection:"row"}}>
                                     <div style={{color:'rgb(115, 116, 118)',borderRadius:20,display:"flex",flexDirection:"row"}}> 
                                        <h3 style={{padding:5,textAlign:"start",justifyContent:"start",background:"rgb(231, 234, 239)",
                                        alignItems:"start",marginLeft:10,borderRadius:5,wordBreak:"break-word",Width:300}}><a 
                                        style={{}}
                                        >{v.msg}</a></h3>
                                    </div>  
                            </div>   
                             
                            <div style={{width:40,height:40,borderRadius:40}}>
                             <img style={{width:"100%",height:"100%"}} src={Kehu}></img>
                            </div>
                            
                          </div>
                         </div> 
                        }
                        </div>
                     </div>
                )
            })}</div>
            <div style={{display:"flex",flexDirection:"row",justifyContent:"center",alignItems:"center"}}>
            
            <InputItem
            clear
            onChange={messageOnChangeItem}
            placeholder="请输入您的信息"
            value={txt}
            >
            </InputItem>
            <Button
            style={{width:200,alignItems:"flex-end"}}
            type="primary" onClick={sendMessages}>发送消息</Button>
            
            </div>


               
       </div>
    )

}
export default OnlineService
